<template>
  <div>
    <!-- 交付经理填写项目定级信息 -->
    <div class="desc-item">
      <div class="form-item">项目实施进度</div>
        <div class="table-title">实施周报</div>
        <div class="execute-progress">
          <el-progress 
            :percentage="lastProgressValue" 
            :stroke-width="20" 
            text-inside 
            :status="lastProgressValue === 100 ? 'success' : ''"
          />
        </div>
        <el-table
          :data="projectInfo.progress"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          style="width: 100%">
          <el-table-column prop="order" label="实施周次"/>
          <el-table-column
            prop="start_time"
            label="开始时间"
            :formatter="row => formatDate(row.start_time, 'YYYY-MM-DD')"
            />
          <el-table-column
            prop="end_time"
            label="结束时间"
            :formatter="row => formatDate(row.end_time, 'YYYY-MM-DD')"
            />
          <el-table-column prop="progress" label="实施进度（%）"/>
          <el-table-column prop="remark" label="备注"/>
          <el-table-column prop="timestamp" label="上报时间"/>
        </el-table>
      <div v-if="isShowApprovalOperation('first')">
        <div class="mb-16 flex">
          <el-button
            class="ml-auto"
            type="primary"
            size="default"
            @click="openModal"
          >上传周报</el-button>
          <el-dialog
            v-model="dialogVisible"
            title="上传周报"
            width="50%"
          >
            <el-form :model="form" label-width="120px">
              <el-form-item label="项目编号">
                <el-input v-model="form.project_code" />
              </el-form-item>
              <el-form-item label="实施周次">
                <el-input-number v-model="form.order" :min="1" />
              </el-form-item>
              <el-form-item label="开始时间">
                <el-date-picker
                  v-model="form.start_time"
                  type="date"
                  placeholder="选择开始时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item label="结束时间">
                <el-date-picker
                  v-model="form.end_time"
                  type="date"
                  placeholder="选择结束时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item label="实施进度">
                <el-select v-model="form.progress" placeholder="请选择进度">
                  <el-option
                    v-for="i in 11"
                    :key="(i-1) * 10"
                    :label="`${(i-1) * 10}%`"
                    :value="(i-1) * 10"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="周报文件">
                <el-upload
                  ref="fileUpload"
                  :auto-upload="false"
                  :on-change="handleFileChange"
                  :on-remove="handleFileRemove"
                  multiple
                >
                  <el-button type="primary">选择文件</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="form.remark" type="textarea" />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm" :loading="isSubmitting">
                  上传周报
                </el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </div>
      <div v-if="projectFiles[processStageName].length > 0">
        <div class="table-title">上传附件</div>
          <FilesUpload
            ref="filesUploadRef"
            :fileTypes="filteredFileTypes"
            :projectInfo="projectInfo"
            :readOnly="!isShowApprovalOperation('first')"
            @getProjectFilesInfo="$emit('getProjectFilesInfo')"
          />
      </div>
      <div v-if="isShowApprovalOperation('first')">
        <div class="form-item">审批信息</div>
        <div class="table-title" > 下一环节 - 建设单位部门经理审批 </div>
        <DynamicDescription
          :descriptions="executeProgressDetails.executeProgressSecondInfoDesc"
          :readOnly="true"
          :column="2"
        />
        <ApprovalOpinion
          ref="approvalOpinionRef"
          v-model="approvalOpinionData" 
          required 
          label="审批意见"
        />
        <div class="mb-16 flex">
          <el-button
            class="ml-auto"
            type="primary"
            size="default"
            @click="approvalProcess('agree', 'projectManager', projectInfo.construction_department_manager_id)"
          >同意</el-button>
        </div>
      </div>
      <!-- 三级经理审批 -->
      <div v-if="isShowApprovalOperation('second')">
        <div class="form-item" style="margin-top: 10px;">审批信息</div>
        <ApprovalOpinion
          ref="approvalOpinionRef"
          v-model="approvalOpinionData" 
          required 
          label="审批意见"
        />
        <div class="mb-16 flex">
          <el-button
            class="ml-auto" 
            type="danger"
            size="default"
            @click="approvalProcess('refuse', 'constructionDepartmentManager')"
          >驳回</el-button>
          <el-button
            type="primary"
            size="default"
            @click="approvalProcess('agree', 'constructionDepartmentManager')"
          >同意</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import * as KmsApi from '@/api/project/kms'
import * as BpmApi from '@/api/project/bpm'
import * as IctApi from '@/api/project/ict'
import DynamicDescription from '@/views/project/projectDetails/components/DynamicDescription.vue'
import FilesUpload from '@/views/project/projectDetails/components//FilesUpload.vue';
import { ref, toRefs, computed } from 'vue'
import { formatDate} from '@/utils/formatTime'
import ApprovalOpinion from '@/views/project/components/ApprovalOpinion.vue'

// emit事件合集
const emit = defineEmits(['getApprovalProcess', 'getProjectInfo', 'getProjectFilesInfo']);

// Props传值
const props = defineProps({
  isShowApprovalOperation: Function,
  projectInfo: Object,
  executeProgressDetails: Object,
  processStageName: String,
  taskName: String,
  role: String,
  processList: Array,
  projectFiles: Object
})
const { isShowApprovalOperation, projectInfo, executeProgressDetails, processStageName, taskName, role, processList, projectFiles } = toRefs(props);
const fileTypes = projectFiles.value[processStageName.value]
const filteredFileTypes = fileTypes.filter(item => item !== "实施周报");

// 审批意见
const approvalOpinionData = ref('同意')
const approvalOpinionRef = ref()
// 创建对文件上传子组件的引用
const filesUploadRef = ref(null);
// 动态详情组件ref对象
const fileUpload = ref();
const dialogVisible = ref(false)
const isSubmitting = ref(false)
const fileList = ref([])

const initialFormState = {
  project_code: '',
  order: 0,
  start_time: '',
  end_time: '',
  progress: 0,
  file_id_list: [],
  remark: '',
  timestamp: ''
};

const form = reactive({ ...initialFormState });

// 计算最后一个进度值的计算属性
const lastProgressValue = computed(() => {
  // 如果 projectInfo.value.progress 不存在或为空数组，返回 0
  if (!projectInfo.value.progress || projectInfo.value.progress.length === 0) {
    return 0
  }
  
  // 获取最后一个进度对象的 progress 值
  const lastProgress = projectInfo.value.progress[projectInfo.value.progress.length - 1]
  
  // 返回最后一个进度值
  return lastProgress.progress
})

const getWeekDates = () => {
  const now = new Date();
  const currentDay = now.getDay();
  
  // 计算本周一的日期
  const monday = new Date(now);
  monday.setDate(now.getDate() - currentDay + (currentDay === 0 ? -6 : 1));
  
  // 计算本周日的日期
  const sunday = new Date(monday);
  sunday.setDate(monday.getDate() + 6);
  
  return {
    start_time: formatDate(monday),
    end_time: formatDate(sunday)
  }
}

const resetForm = () => {
  Object.assign(form, { ...initialFormState });
  if (fileUpload.value) {
    fileUpload.value.clearFiles();
  }
}

const openModal = () => {
  dialogVisible.value = true
  // 设置时间戳为当前时间
  form.project_code = projectInfo.value.project_code
  form.timestamp = new Date().toISOString()

  // 预填写本周的开始和结束时间
  const { start_time, end_time } = getWeekDates()
  form.start_time = start_time
  form.end_time = end_time

  // 预填写实施周次
  form.order = (!projectInfo.value.progress || 
              projectInfo.value.progress.length === 0) 
              ? 1 
              : projectInfo.value.progress.length + 1
}

const handleFileChange = (uploadFile, uploadFileList) => {
  fileList.value = uploadFileList
}

const handleFileRemove = (uploadFile, uploadFileList) => {
  fileList.value = uploadFileList
}

const uploadFile = async (file) => {
  const uploadData = new FormData()
  uploadData.append('resource_name', projectInfo.value.project_name || '')
  uploadData.append('resource_id', projectInfo.value.project_code || '')
  uploadData.append('file_type', '实施周报')
  uploadData.append('file', file)

  try {
    const response = await KmsApi.uploadFile(uploadData)
    return response
  } catch (error) {
    console.error('File upload error:', error)
    throw error
  }
}

const submitForm = async () => {
  if (isSubmitting.value) return
  isSubmitting.value = true

  try {
    // 上传所有文件
    const fileIds = []
    for (const file of fileList.value) {
      const fileId = await uploadFile(file.raw)
      fileIds.push(fileId)
    }

    form.file_id_list = fileIds
    // 提交周报信息
    const response = await IctApi.addWeeklyReports(form)
    emit('getProjectInfo')
    ElMessage.success('周报上传成功')
    dialogVisible.value = false
    // 重置表单
    resetForm()
    fileList.value = []
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('提交失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

const approvalProcess = async (result, currentRole, nextRoleId) => {
  try {
    if (filesUploadRef.value && !filesUploadRef.value?.validateFiles()) {
      return;
    }
    if(approvalOpinionRef.value) {
      await approvalOpinionRef.value.validateForm()
    }
    // 表单验证通过，执行提交逻辑
    ElMessageBox.confirm(
      `
        是否${result === 'agree' ? '同意' : '驳回'}该流程单？
        ${result === 'agree' ? '<p><span style="color: red;">请确认周报上传全部完成，流程提交后将无法上传！</span></p>' : ''}
      `,
      '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true
    }).then(async () => {      
      if (result === 'agree') {
        const agreeProcessData = {
          assignedUserIds: [nextRoleId],
          id: processList.value[0].id,
          reason: approvalOpinionData.value || '同意',
          copyUserIds: [],
          variables: {}
        }

        const agreeData = {
          update: true,
          project_index_do: projectInfo.value,
          task_approve_req_vo: agreeProcessData
        }

        if (currentRole === 'projectManager') {
          await IctApi.agreeProjectProcess(agreeData).then(() => {
            emit('getApprovalProcess')
            emit('getProjectInfo')
          })
        } else {
          await IctApi.agreeExecuteProgressDepartmentManagerProcess(agreeData).then(() => {
            emit('getApprovalProcess')
            emit('getProjectInfo')
          })
        }

      } else if (result === 'refuse') {
        const refuseData = {
          id: processList.value[0].id,
          reason: approvalOpinionData.value || '不同意'
        }
        await IctApi.refuseExecuteProgressProcess(refuseData).then(() => {
          emit('getApprovalProcess')
        })
      }
      ElMessage({
        type: 'success',
        message: '提交成功'
      })
    })
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '请按照格式要求填写信息'
    })
  }
  
}

</script>

<style lang="scss" scoped>
@import url('@/views/project/projectDetails/styles/transfer.css');

.execute-progress .el-progress--line {
  margin-bottom: 15px;
}

</style>